//
//  PLMediator.swift
//  swiftProject
//
//  Created by 孟祥群 on 2018/4/17.
//  Copyright © 2018年 孟祥群. All rights reserved.
//

import UIKit

class PLMediator: NSObject {
    static let shareNetWorkBase = PLMediator();
    
    func performActionWithUrl(url:NSURL,completion:@escaping(NSDictionary)->()) -> AnyObject! {
        if url.scheme! != "aaa" {
            let  number = NSNumber(value:false)
            return number
        }
        let params:NSMutableDictionary = [:]
        let urlString = url.query
        for param in urlString!.components(separatedBy: "&") {
            let elts = param.components(separatedBy: "=")
            if elts.count < 2 {
                continue;
         }
            params .setObject(elts.last ?? "", forKey: elts.first! as NSCopying)
        
      }
      let actionName = url.path!.replacingOccurrences(of: "/", with: "")
        if actionName.hasPrefix("native") {
            return NSNumber(value:false)
        }
        let result = self.performTarget(targetName: url.host!, action: actionName, params: params)
        completion(["result":result ?? ""])
        
        return result
    }
    
    func performTarget(targetName:String,action actionName:String,params:NSDictionary) -> AnyObject? {
        
        let targetClassString = String(format: "swiftProject.Target_%@", targetName)
        var actionString:String
        let dic = params as Dictionary
        !dic.isEmpty ? (actionString = String(format: "Action_%@WithParams:", actionName)) : (actionString = String(format: "Action_%@", actionName))
        let targetClass = NSClassFromString(targetClassString) as? NSObject.Type
        
        let  target = targetClass?.init()
        let action  = NSSelectorFromString(actionString) 
        
        if target == nil {
            return nil
        }
        
        if target!.responds(to: action) {
            
            return !dic.isEmpty ? target!.perform(action, with: params).takeRetainedValue() : target!.perform(action).takeRetainedValue()
        }else  {
            
            let action = NSSelectorFromString("notFound:")
            if (target!.responds(to: action)) {
           return !dic.isEmpty ? target!.perform(action, with: params).takeRetainedValue() : target!.perform(action).takeRetainedValue()
            }else {
                return nil
            }
      }
  }
}
